package com.chushouya.manager.service.api.impl;

import com.general.framework.core.lang.Validate;
import com.chushouya.manager.dao.entity.VisitAreaEntity;
import com.chushouya.manager.dao.repository.VisitAreaRepository;
import com.chushouya.manager.dto.admin.visitarea.VisitAreaQuery;
import com.chushouya.manager.dto.api.doorservice.DoorServiceCheckRequest;
import com.chushouya.manager.dto.api.doorservice.DoorServiceCheckResponse;
import com.chushouya.manager.service.api.DoorServiceApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 上门服务API服务实现类
 * 
 * @author chushouya
 */
@Service
@Slf4j
public class DoorServiceApiServiceImpl implements DoorServiceApiService {

    @Resource
    private VisitAreaRepository visitAreaRepository;

    @Override
    public DoorServiceCheckResponse checkDoorServiceAvailable(DoorServiceCheckRequest request) {
        Validate.isNull(request, "请求参数不能为空");
        return checkDoorServiceAvailable(request.getDistrictCode());
    }

    @Override
    public DoorServiceCheckResponse checkDoorServiceAvailable(String districtCode) {
        Validate.isBlank(districtCode, "区域代码不能为空");
        
        log.info("检查区域代码 {} 是否支持上门服务", districtCode);
        
        try {
            // 将字符串转换为Long类型的区域代码
            Long districtCodeLong = Long.parseLong(districtCode);
            
            // 从数据库查询是否存在该区域代码且状态为启用
            VisitAreaQuery query = new VisitAreaQuery();
            query.setDistrictCode(districtCodeLong);
            
            List<VisitAreaEntity> visitAreas = visitAreaRepository.selectList(query);
            
            // 检查是否找到匹配的区域且状态为启用（假设status=1表示启用）
            boolean isSupported = visitAreas.stream()
                    .anyMatch(area -> area.getStatus() != null && area.getStatus() == 1);
            
            if (isSupported) {
                log.info("区域代码 {} 支持上门服务", districtCode);
                return DoorServiceCheckResponse.success("该区域支持上门服务");
            } else {
                log.info("区域代码 {} 暂不支持上门服务", districtCode);
                return DoorServiceCheckResponse.fail("该区域暂不支持上门服务，请选择邮寄方式");
            }
        } catch (NumberFormatException e) {
            log.error("区域代码格式错误: {}", districtCode, e);
            return DoorServiceCheckResponse.fail("区域代码格式错误");
        } catch (Exception e) {
            log.error("检查上门服务可用性时发生异常: {}", e.getMessage(), e);
            return DoorServiceCheckResponse.fail("系统异常，请稍后重试");
        }
    }
}
